﻿﻿using NavigateDemo.ViewModels;

namespace NavigateDemo.Services
{
    public class NavigationService
    {
        private readonly IServiceProvider _serviceProvider;
        private ViewModelBase? currentViewModel;
        
        // 构造函数，通过依赖注入获取服务提供者
        public NavigationService(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
        }
        
        public ViewModelBase? CurrentViewModel
        {
            get => currentViewModel;
            set
            {
                currentViewModel = value;
                // 每次属性改变即导航的时候都会执行这个事件
                // 我们在MainVM中实例化事件(将需要导航的PageVM传递给MainVW)
                CurrentViewModelChanged?.Invoke();
            }
        }
        
        public event Action? CurrentViewModelChanged;
        
        public void NavigateTo<T>() where T : ViewModelBase
        {
            var viewModel = _serviceProvider.GetService<T>();
            if (viewModel == null)
            {
                throw new InvalidOperationException($"无法创建视图模型 {typeof(T).Name}，请检查是否已正确注册到依赖注入容器中。");
            }
            CurrentViewModel = viewModel;
        }
        
        // 添加支持传递参数的导航方法
        public void NavigateTo<T>(Action<T> parameterAction) where T : ViewModelBase
        {
            if (parameterAction == null)
            {
                throw new ArgumentNullException(nameof(parameterAction));
            }
            
            var viewModel = _serviceProvider.GetService<T>();
            if (viewModel == null)
            {
                throw new InvalidOperationException($"无法创建视图模型 {typeof(T).Name}，请检查是否已正确注册到依赖注入容器中。");
            }
            
            // 在设置当前ViewModel之前应用参数
            parameterAction(viewModel);
            CurrentViewModel = viewModel;
        }
    }
}
